import { message } from 'antd';
import { ApiResponse } from '../models/common';

const BASE_URL = 'http://localhost:8101/api';

interface RequestOptions extends RequestInit {
  data?: any;
  params?: Record<string, any>;
}

/**
 * 统一请求处理函数
 * @param url 请求路径
 * @param options 请求选项
 * @returns Promise<ApiResponse<T>>
 */
async function request<T = any>(url: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
  const { data, params, ...rest } = options;
  
  // 处理URL参数
  let requestUrl = `${BASE_URL}${url}`;
  if (params) {
    const queryString = Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
      .join('&');
    requestUrl = `${requestUrl}${requestUrl.includes('?') ? '&' : '?'}${queryString}`;
  }

  // 默认请求头
  const headers = new Headers({
    ...rest.headers,
  });

  // 如果不是FormData，设置Content-Type为application/json
  if (!(data instanceof FormData)) {
    headers.set('Content-Type', 'application/json');
  }

  // 获取并添加token
  const token = localStorage.getItem('token');
  if (token) {
    headers.append('Authorization', `Bearer ${token}`);
  }

  try {
    const response = await fetch(requestUrl, {
      ...rest,
      headers,
      body: data ? (data instanceof FormData ? data : JSON.stringify(data)) : undefined,
    });

    // 处理HTTP错误
    if (!response.ok) {
      if (response.status === 401) {
        // 未授权，清除登录信息并跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        window.location.href = '/login';
        return {
          code: 401,
          message: '登录已过期，请重新登录',
          data: null,
          success: false,
        };
      }
      
      return {
        code: response.status,
        message: `请求失败: ${response.statusText}`,
        data: null,
        success: false,
      };
    }

    // 解析响应数据
    const result = await response.json();
    return result as ApiResponse<T>;
  } catch (error) {
    console.error('请求错误:', error);
    message.error('网络错误，请稍后重试');
    return {
      code: 500,
      message: '网络错误，请稍后重试',
      data: null,
      success: false,
    };
  }
}

// 导出便捷方法
// 导出request函数
export { request };

export default {
  get: <T = any>(url: string, params?: Record<string, any>) => 
    request<T>(url, { method: 'GET', params }),
  
  post: <T = any>(url: string, data?: any) => 
    request<T>(url, { method: 'POST', data }),
  
  put: <T = any>(url: string, data?: any) => 
    request<T>(url, { method: 'PUT', data }),

  delete: <T = any>(url: string, data?: any) => 
    request<T>(url, { method: 'DELETE', data }),
};